<?php
class CModule extends CRecord
{
	static $current;
	public $error_messages = array();
	public $cache_time = 0;
	public $cache_name;

	/**
	 * Constructor
	 *
	 * @param array $data
	 */
	function __construct($data) {
	  parent::__construct($data);

	  if (isset($data['cache_time'])) {
	    $this->cache_time = intval($data['cache_time']);
	    $this->cache_name = 'module'.$data['name'];
      $ret = CSystem::$cachelayout->get($this->getCacheName());
      if (null!=$ret) {
        foreach ($ret as $key=>$value) {
          $this->$key = $value;
        }
        $this->data['id'] = $data['id'];
        $this->data['parent_id'] = $data['parent_id'];
        return;
      }
    }

		$last = &CModule::$current;
		CModule::$current = &$this;
		$this->init();
		CModule::$current = &$last;
		if ($this->cache_time) {
		  CSystem::$cachelayout->set($this->getCacheName(), $this, $this->cache_time);
		}
	}

	/**
	 * Clear data cache for module, listing
	 *
	 */
	function clearCache() {
		if (isset($this->data['cache_time'])) {
			CSystem::$cachelayout->delete($this->getCacheName());
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $name
	 * @param unknown_type $params
	 * @param unknown_type $module
	 */
	function extend_layout($name, $params, $module = false) {
		$name .= '.tpl';
		if(CFile::exists($layout = $this->path.'/'.$name)) {
			CForm($layout)->parse($params);
		} else {
			$parents = class_parents($this);
			foreach($parents as $parent) {
				if(CFile::exists($layout = CModule::module_path($parent).'/'.$name)) {
					CForm($layout)->parse($params);
					return;
				}
			}
		}
	}

	function init() {
	}

	function submit() {
		if ($func = request('cmd')) {
			$func = 'on_'.$func;
			if (method_exists($this, $func)) {
				try {
					$this->$func();
				} catch (Exception $e) {
					$this->error('Error', $e->getMessage());
				}
				if ($script = portal()->script) {
					echo '<script type="text/javascript">'.$script.'</script>';
				}
				CSystem::end();
			}
		}
	}

	/**
	 * Name of cache
	 *
	 * @return string
	 */
	function getCacheName() {
	  return $this->cache_name;
	}

	function cache_draw() {
	  $this->draw();
	}

	function draw() {
	}

	function path() {
		return $this->path;
	}

	function error($input = false, $message = false) {
		if($message) {
			$this->error_messages[] = array('input'=>$input, 'message' => $message);
		} else {
			if ($input) {
				return CList($this->error_messages)->filter(array('input'=>$input));
			} else {
				return $this->error_messages;
			}
		}
	}

	function is_error() {
		return $this->error_messages != array();
	}

	function check($name, $options = array()) {
		require_once ROOT_DIR.'lib/utils/CInput.php';
		try {
			CInput($name, $options)->check();
		} catch (Exception $e) {
			$this->error('Error', $e->getMessage());
		}
	}

	function error_messages($layout = false) {
		if(!$layout) {
			$layout = 'lib/form/error_messages.tpl';
		}
		CForm($layout)->parse(array(
			'items' => $this->error_messages
		));
	}

	function input_error($input, $layout = false) {
		if(!$layout) {
			$layout = 'lib/portal/input_error.tpl';
		}
		CForm($layout)->parse(array(
			'items' => $this->error($input)
		));
	}

	function can_edit() {
		return user()->can_edit();
	}

	function can_add() {
		return user()->can_add();
	}

	function can_delete() {
		return user()->can_delete();
	}

	function can_view() {
		return user()->can_view();
	}

	function can_view_detail() {
		return user()->can_view_detail();
	}

	function can_moderator() {
		return user()->can_moderator();
	}

	function can_developer() {
		return user()->can_developer();
	}

	function can_admin() {
		return user()->can_admin();
	}

	function can_editor($category_id = -1, $content_type = 0) {
		if($this->can_admin()) {
			return true;
		}
		if($category_id == -1) {
			$category_id = request('category_id');
		}
		return CTable('content_privilege')->select(array('user_id'=>user()->id, 'category_id'=>$category_id, 'portal_id'=>portal()->id, 'type'=>$content_type));
	}

	function frame($title, $content, $path = false) {
		if(!$path) {
			$path = module()->setting('layout',$this->path().'/default.tpl');
		}
		$params = array(
			'title' => $title,
			'layout_path' => substr($path,0,strrpos($path,'/')),
			'content' => $content
		);

		$layout = str_replace('{region(\'center\')}','{content}',file_get_contents($path));
		if(!request('module')) {
			$script = CForm::strip_script($layout);
		}

		eval(' ?>'.CFormLayout($layout)->parse().'<?php ');
		if(!request('module')) {
			portal()->script .= output()->get(eval(' ?>'.CFormLayout($script)->parse()));
		}
	}

	function get_frame($path = '', $type = '') {
		if(!$path) {
			$path = module()->setting('layout',$this->path().'/default.tpl');
		}
		if(!$type) {
			$type = module()->setting('type');
		}
		$name = 'framecache.'.$path.$type;
		if (!($frame=CSystem::$cachelayout->get($name))) {
  		$layout = str_replace('{setting(\'type\')}','{type}',file_get_contents($path));
  		$script = CForm::strip_script($layout);
  		$pos = strpos($layout,'{region(\'center\')}');
  		$params = array(
  			'title' => '[[title]]',
  			'layout_path' => substr($path,0,strrpos($path,'/')),
  			'type' => $type
  		);

  		$frame = array(
    		'begin' => output()->get(@eval(' ?>'.CFormLayout(substr($layout,0,$pos))->parse())),
    		'end' => output()->get(@eval(' ?>'.CFormLayout(substr($layout,$pos + strlen('{region(\'center\')}')))->parse())),
   			'script' => output()->get(eval(' ?>'.CFormLayout($script)->parse()))
 			);
 			CSystem::$cachelayout->set($name, $frame);
		}

		if (isset($frame['script'])) portal()->script .= $frame['script'];
		return $frame;
	}

	function frame_title($frame_code, $title) {
		return str_replace('[[title]]',$title,$frame_code);
	}

	static function module_path($class_name) {
		if(isset(CPortal::$components['MODULE.'.$class_name]) and $module = CPortal::$components['MODULE.'.$class_name]) {
			return $module['path'];
		}
	}

	function skin($st) {
		return str_replace(array('{root_url}', '{static_url}'),array(CPortal::$root_url, CPortal::$static_url),$st);
	}
}

function CModule($id) {
  return new CModule($id);
}

function error_messages($layout = false) {
	try {
		return module()->error_messages($layout);
	} catch(Exception $e) {
	}
}

function input_error($input, $layout = false) {
	try {
		return module()->input_error($input, $layout);
	} catch(Exception $e) {
	}
}

function error($input = false) {
	try {
		return module()->error($input);
	} catch(Exception $e) {
	}
}

function &module() {
	if(CModule::$current) {
		return CModule::$current;
	} else {
		$block = new CModule(array('id'=>0));
		return $block;
	}
}

function jm() {
	return 'SYS.blocks['.module()->id.']';
}

function __autoload($class_name) {
	if(strpos($class_name,'::')) {
		$class_name = substr($class_name, strrpos($class_name,'::')+2);
		exit();
	}

	if($path = CModule::module_path($class_name)) {
		require_once $path.'/class.php';
	} else if(file_exists('lib/utils/'.$class_name.'.php')) {
		require_once 'lib/utils/'.$class_name.'.php';
	}
}

function setting($name, $default = NULL) {
	return module()->setting($name, $default);
}

function module_path() {
	return module()->path();
}
?>